package com.apache.passport.service.plugins;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.database.constant.Validator;
import com.apache.database.db.IDao;
import com.apache.passport.aop.LoginAopTimer;
import com.apache.passport.entity.SynInfo;
import com.apache.passport.entity.UctUser;
import com.apache.passport.manager.SynInfoManager;
import com.apache.rpc.client.AbstractProtocolService;
import com.apache.rpc.client.HttpProtocolService;
import com.apache.rpc.client.SocketProtocolService;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * description:  用户信息同步
 *
 * @author Hou Dayu 创建时间：2016-12-23
 */
public class SynInfoPlugin implements PluginConnector {

    private static final Logger log = LoggerFactory.getLogger(LoginAopTimer.class);

    protected IDao synInfoDao;

    private SynInfoManager synInfoManager;

    public void setSynInfoDao(IDao synInfoDao) {
        this.synInfoDao = synInfoDao;
    }

    public void setSynInfoManager(SynInfoManager synInfoManager) {
        this.synInfoManager = synInfoManager;
    }

    @Override
    public Object execute(ParamsVo arg0) throws Exception {
        String sysEname = (String) arg0.getParams("sysEname");
        UctUser uctUser = (UctUser) arg0.getParams("user");
        //客户端返回信息
        String rtn = "";
        ResultEntity result = new ResultEntity();
        if (!Validator.isEmpty(sysEname)) {

            Map<String, AbstractProtocolService> services = new HashMap<String, AbstractProtocolService>();
            services.put("http", new HttpProtocolService());
            services.put("socket", new SocketProtocolService());
            SynInfo synInfo = new SynInfo();
            ParamsVo<SynInfo> mvo = new ParamsVo<SynInfo>();
            mvo.setParams("sysEname", sysEname);
            mvo.setMethodKey("sysEnameQuery");
            result = (ResultEntity) synInfoManager.execute(mvo);
            if (result.getEntity() instanceof SynInfo) {
                synInfo = (SynInfo) result.getEntity();
                AbstractProtocolService ps = (AbstractProtocolService) services
                        .get(synInfo.getSynUseAgree());
                ps.setRegister(synInfo.getSynSeraddr(), synInfo.getSynSockport(),
                        synInfo.getSynSeraddr());
                //String sndMsg = pariseXml(uctUser, synInfo.getSynParamet());
                Map usermap = uctUser.getValues(uctUser);
                ResultEntity entity = ps.doService("ssoService", "userOwRegService", usermap);
                rtn = String.valueOf(entity.getEntity());
                if (Validator.isNull(rtn)) {
                    result.setMessage("发送失败或客户端为异常");
                    log.info("passport msg:[{}]", "发送失败或客户端为异常");
                } else {
                    result.setMessage("发送成功");
                    log.info("passport msg:[{}]", "发送成功");
                }

                result.setEntity(rtn);
                log.info("receive msg:[{}]", rtn);
            }

        }
        return result;
    }

    /**
     * description:拼接发送的报文
     *
     * @param uctUser
     * @param synParamet
     * @return
     */
    private String pariseXml(UctUser uctUser, String synParamet) {
        String xml = "";
        Document doc = new Document();
        Element root = new Element("xml-body");
        Element head = new Element("Head");
        Element body = new Element("Body");
        //头 begin
        Element version = new Element("Version");
        version.setText("1.0");
        Element methodCode = new Element("MethodCode");
        methodCode.setText("userOwRegService");
        Element beanId = new Element("BeanId");
        beanId.setText("ssoService");
        Element paramType = new Element("ParamType");
        paramType.setText("xml");

        head.addContent(version);
        head.addContent(methodCode);
        head.addContent(beanId);
        head.addContent(paramType);
        //头 end

        //体 begin,参数列表用","半角逗号分隔
        String[] param = synParamet.split(",");
        //获取当前对象中所有的值
        Map<String, String> map = uctUser.getValues(uctUser);
        for (int i = 0; i < param.length; i++) {
            Element bodyChild = null;
            if (Validator.isNull(param[i])) {
                bodyChild = new Element("<Null" + i + ">");
                bodyChild.setText("此值key为null或空格");
            } else {
                bodyChild = new Element(param[i]);
                bodyChild.setText(map.get(param[i]) == null ? "" : map.get(param[i]));
            }
            body.addContent(bodyChild);
        }
        //体 end
        root.addContent(head);
        root.addContent(body);

        doc.addContent(root);
        XMLOutputter outputter = null;
        Format format = Format.getRawFormat();
        format.setEncoding("UTF-8");
        format.setIndent("    ");
        outputter = new XMLOutputter(format);
        xml = outputter.outputString(doc);
        return xml;
    }
}
